﻿
@{
    ViewBag.Title = "CouponEdit";
    Layout = "~/Views/Shared/_LayoutBlank.cshtml";
}


<link rel="stylesheet" type="text/css" href="/Scripts/wangEditor/css/wangEditor.min.css">
<script type="text/javascript" src='/Scripts/wangEditor/js/wangEditor.min.js'></script>

<style>
    .wangEditor-container .wangEditor-txt p,
    .wangEditor-container .wangEditor-txt h1,
    .wangEditor-container .wangEditor-txt h2,
    .wangEditor-container .wangEditor-txt h3,
    .wangEditor-container .wangEditor-txt h4,
    .wangEditor-container .wangEditor-txt h5 {
        margin: 0px 0;
        line-height: 1.8;
    }
</style>

<style type="text/css">
    .divImageMaterialContainer {
        width: 170px;
        float: left;
        margin-right: 10px;
        margin-top: 0px;
        background-color: #FFF;
    }

    .tableImageMaterialContainer {
        width: 100%;
        border-collapse: collapse;
        border: solid #E7E7EB;
        border-width: 1px 0 0 1px;
    }

        .tableImageMaterialContainer td {
            border: 1px solid #E7E7EB;
        }
</style>

<script>

    var _id = getQueryString("id");

    var _mode = "create";//modify
    var _validator;

    var _divStockEditHtml;
    var _stockAdjustmentType = "increment"; // decrement
    var _stockChanged = false;

    var _data = null;

    var _editor;

    $(document).ready(function () {

        _divStockEditHtml = $("#divStockEdit").html();
        $("#divStockEdit").html("");

        $("[keyenter]").keypress(function (e) {
            if (e.keyCode == 13) {
                save();
            }
        });

        $("#txtImageUrl").blur(function () {
            loadImage();
        });

        $('#selectInfiniteStock').change(selectInfiniteStockChange);

        _validator = $("#form").validate({
            onfocusout: false,
            onkeyup: false,
            showErrors: showValidationErrors,
            rules: {
                "txtName": "required",
                "txtStock": {
                    required: true,
                    number: true,
                    digits: true,
                    range: [0, 1000000]
                }
            },
            messages: {
                "txtName": "请输入卡券名称；",
                "txtStock": {
                    required: "请输入库存数量；",
                    number: "库存数量请输入有效整数字；",
                    digits: "库存数量请输入有效整数字；",
                    range: "库存数量请介于 0 到 1000000 之间；"
                }
            }
        });

        _editor = new wangEditor('divDescriptionEditor');
        _editor.config.menus = [
        'source',
        '|', 'bold', 'underline', 'italic', 'strikethrough', 'eraser', 'forecolor', 'bgcolor',
        '|', 'quote', 'fontfamily', 'fontsize', 'head', 'unorderlist', 'orderlist', 'alignleft', 'aligncenter', 'alignright',
        '|', 'link', 'unlink', 'table',
        '|', 'undo', 'redo', 'fullscreen'
        ];
        _editor.create();

        load();
    });

    function selectInfiniteStockChange() {
        var infiniteStock = $("#selectInfiniteStock").children('option:selected').val();

        if (infiniteStock == "true") {
            $("#txtStock").attr("disabled", "disabled");

            if ($("#txtStock").val() == "") {
                $("#txtStock").val("0");
            }

            $("#trStock").hide();

        } else {
            if (_mode == "create") {
                $("#txtStock").removeAttr("disabled");
            }

            //if ($("#txtStock").val() == "0") {
            //    $("#txtStock").val("");
            //}

            $("#trStock").show();
        }
    }

    function load() {
        if (_id == undefined || _id == "") {
            selectInfiniteStockChange();
            return;
        }

        _mode = "modify";
        $("#spanTitle").html("修改卡券");
        $("#btnRemove").show();
        $("#txtStock").attr("disabled", true);
        $("#btnIncrement").show();
        $("#btnDecrement").show();

        var loadLayerIndex = layer.load(0, {
            shade: [0.2, '#fff']
        });

        $.ajax({
            url: "/Api/Coupon/GetCoupon?id=" + _id,
            type: "POST",
            dataType: "json",
            success: function (data, status, jqXHR) {
                layer.close(loadLayerIndex);
                if (data.Success) {
                    _data = data.Data;
                    $("#txtName").val(_data.Name);
                    $("#txtImageUrl").val(_data.ImageUrl);
                    $("#selectInfiniteStock").find("option[value='" + _data.InfiniteStock + "']").attr("selected", true);
                    $("#txtStock").val(_data.Stock);
                    $("#txtCondition").val(_data.Condition);
                    _editor.$txt.html(_data.Description);

                    selectInfiniteStockChange();
                    loadImage();

                } else {
                    layerAlert(data.Message);
                }
            },
            error: function (xmlHttpRequest) {
                layer.close(loadLayerIndex);
                alert("Error: " + xmlHttpRequest.status);
            }
        });
    }

    function save() {
        if (_validator.form() == false) {
            return;
        }

        var loadLayerIndex = layer.load(0, {
            shade: [0.2, '#fff']
        });

        var url = "/Api/Coupon/CreateCoupon";
        if (_mode == "modify") {
            url = "/Api/Coupon/UpdateCoupon";
        }

        if (_data == undefined || _data == null) {
            _data = new Object();
        }

        _data.Name = $("#txtName").val();
        _data.ImageUrl = $("#txtImageUrl").val();
        _data.InfiniteStock = $("#selectInfiniteStock").val();
        _data.Stock = $("#txtStock").val();
        _data.Condition = $("#txtCondition").val();
        _data.Description = _editor.$txt.html();

        $.ajax({
            url: url,
            type: "POST",
            dataType: "json",
            data: JSON.stringify(_data),
            success: function (data, status, jqXHR) {
                layer.close(loadLayerIndex);
                if (data.Success) {
                    var index = parent.layer.getFrameIndex(window.name);
                    if (_mode == "create") {
                        parent.loadDataAndCloseLayer(index);
                    } else {
                        parent.loadDataOnPageAndCloseLayer(index);
                    }
                } else {
                    layerAlert(data.Message);
                }
            },
            error: function (xmlHttpRequest) {
                layer.close(loadLayerIndex);
                alert("Error: " + xmlHttpRequest.status);
            }
        });
    }

    function removeData() {
        if (_id == undefined || _id == "") {
            return;
        }

        var msg = "是否确认删除？<br/>注意：已派发到会员的卡券不会被删除，仍可继续核销。"

        var confirmLayerIndex = layer.confirm(msg, {
            btn: ['确认', '取消'], //按钮
            shade: [0.4, '#393D49'],
            title: false,
            closeBtn: false,
            shift: _layerShift
        }, function () {
            layer.close(confirmLayerIndex);

            var loadLayerIndex = layer.load(0, {
                shade: [0.2, '#fff']
            });

            $.ajax({
                url: "/Api/Coupon/RemoveCoupon?id=" + _id,
                type: "POST",
                dataType: "json",
                success: function (data, status, jqXHR) {
                    if (data.Success) {
                        var index = parent.layer.getFrameIndex(window.name);
                        parent.loadDataOnPageAndCloseLayer(index);

                    } else {
                        layer.closeAll();
                        layerAlert(data.Message);
                    }
                },
                error: function (xmlHttpRequest) {
                    layer.closeAll();
                    alert("Error: " + xmlHttpRequest.status);
                }
            });
        });
    }

    function showIncrement() {
        layer.open({
            type: 1,
            area: ['220px', '170px'], //宽高
            closeBtn: false,
            title: "",
            shift: _layerShift,
            content: _divStockEditHtml,
            success: function (layero, index) {
                _stockAdjustmentType = "increment";

                $(layero).focus();
            }
        });
    }

    function showDecrement() {
        layer.open({
            type: 1,
            area: ['220px', '170px'], //宽高
            closeBtn: false,
            title: "",
            shift: _layerShift,
            content: _divStockEditHtml,
            success: function (layero, index) {
                $(layero).focus();

                _stockAdjustmentType = "decrement";

                $("#divStockEditTitle").html("消减库存");

            }
        });
    }

    function stockAdjustment() {
        var txtChangeStockValidationMessage = "请输入要增加的库存数量；";

        if (_stockAdjustmentType == "decrement") {
            txtChangeStockValidationMessage = "请输入要消减的库存数量；";
        }

        if ($("#formStockEdit").validate({
            onfocusout: false,
            onkeyup: false,
            showErrors: showValidationErrors,
            rules: {
                "txtChangeStock": {
            required: true,
            number: true
        }
        },
            messages: {
                "txtChangeStock": {
            required: txtChangeStockValidationMessage,
            number: "请输入有效整数字；"
        }
        }
        }).form() == false) {
            return;
        }

        var quantity = $("#txtChangeStock").val();

        closeAllLayer();

        var loadLayerIndex = layer.load(0, {
            shade: [0.2, '#fff']
        });

        var args = new Object();
        args.Id = _data.Id;
        args.Quantity = quantity;

        var url = "/Api/Coupon/StockIncrement";

        if (_stockAdjustmentType == "decrement") {
            url = "/Api/Coupon/StockDecrement";
        }

        $.ajax({
            url: url,
            type: "POST",
            dataType: "json",
            data: JSON.stringify(args),
            success: function (data, status, jqXHR) {
                layer.close(loadLayerIndex);
                if (data.Success) {
                    _stockChanged = true;
                    $("#txtStock").val(data.Data.Stock);
                    layerAlert("该卡券的库存数量已调整到：" + data.Data.Stock);
                } else {
                    layerAlert(data.Message);
                }
            },
            error: function (xmlHttpRequest) {
                layer.close(loadLayerIndex);
                alert("Error: " + xmlHttpRequest.status);
            }
        });
    }

    function cancel() {
        var index = parent.layer.getFrameIndex(window.name);
        if (_stockChanged) {
            parent.loadDataOnPageAndCloseLayer(index);
        }
        else {
            parent.layer.close(index); //再执行关闭
        }
    }

    function loadImage() {
        $("#image").attr("src", $("#txtImageUrl").val());
    }

    function uploadFile() {
        __showFileUpload(getUploadResult);
    }

    function getUploadResult(fileServiceAddress, result) {
        var url = fileServiceAddress + result.Data.StoreFilePath;
        $("#txtImageUrl").val(url);
        loadImage();
    }

    function removeImage() {
        $("#txtImageUrl").val("");
        loadImage();
    }

    ////详细图片

    function uploadDescriptionFile() {
        __showFileUpload(getUploadDescriptionFileResult);
    }

    function getUploadDescriptionFileResult(fileServiceAddress, result) {
        var url = fileServiceAddress + result.Data.StoreFilePath;
        _editor.$txt.append("<img src='" + url + "' style='max-width:100%' />");
    }

    function closeAllLayer() {
        layer.closeAll();
    }

</script>

<script id="imageListTemplate" type="text/html">

    {{# for(var i = 0, len = d.length; i < len; i++){ }}
    <div class="divImageMaterialContainer">
        <table class="tableImageMaterialContainer">
            <tr>
                <td height="150" align="center"><img style="max-width:166px; max-height:100%" src="{{ d[i].Url }}" /></td>
            </tr>
            <tr>
                <td height="30" valign="middle" bgcolor="#F4F5F9">
                    <div>
                        <div style="float: right; margin-right: 10px;">
                            <img src="/Content/Images/ico_remove.jpg" width="20" height="20" onclick="removeDetailImageItem('{{ d[i].Id }}')">
                        </div>
                        <div style="clear: both"></div>
                    </div>
                </td>
            </tr>
        </table>

    </div>

    {{# } }}
    <div style="clear:both"></div>

</script>

<script id="divStockEdit" type="text/html">
    <div style="margin-left:10px; margin-right:10px;margin-top:20px; margin-bottom:10px;">
        <div style="width:100%;">
            <div>
                <span id="divStockEditTitle" class="font_blue_20">增加库存</span>
            </div>
            <div style="width:100%; margin-left:0px; margin-top:20px;">
                <form id="formStockEdit">
                    <table width="90%" border="0" align="center" cellpadding="0" cellspacing="0">
                        <tr>
                            <td width="130" height="36">
                                <input id="txtChangeStock" name="txtChangeStock" type="text" class="input_16" style="width:96%; " keyenter />
                            </td>
                        </tr>
                    </table>
                </form>
            </div>
            <div style=" width:100%; margin-top:20px; margin-left:0px;">
                <div style="float:right">
                    <input name="btnSave" type="button" class="btn_blue" id="btnSave" value="确 定" onclick="stockAdjustment()" />
                    <input name="btnCancel" type="button" class="btn_blue" id="btnCancel" value="取 消" onclick="closeAllLayer()" />
                </div>
                <div style="clear:both">
                </div>
            </div>
        </div>
    </div>
</script>


<div style="margin-left:20px; margin-right:20px; margin-top:20px;">
    <span id="spanTitle" class="font_black_24">卡券</span>
</div>

<div style=" background-color:#ccc; margin-left:20px; margin-right:20px; margin-top:10px; height:1px;">
</div>

<div style=" position:absolute; overflow:auto ;margin-top:25px;left:30px; right:30px; bottom:60px; top:50px; ">

    <form id="form">
        <table width="100%" border="0" cellspacing="0" cellpadding="0">
            <tr>
                <td width="110" height="36">名称：</td>
                <td><input id="txtName" name="txtName" type="text" class="input_16" style="width:96%; " maxlength="25" keyenter /></td>
            </tr>
            <tr>
                <td valign="top">
                    <div style="margin-top:5px;">
                        图片：
                    </div>
                </td>
                <td valign="top">
                    <div class="divBorder_gray" style="margin-bottom:5px;width:96%;">
                        <div style="padding:5px;">
                            <table width="100%" border="0" cellspacing="0" cellpadding="0">
                                <tr>
                                    <td width="120"><img id="image" alt="" style="max-height:100px;" /></td>
                                    <td align="right">
                                        <input id="txtImageUrl" name="txtImageUrl" type="hidden" class="input_16" style="width:96%; " maxlength="500" keyenter />
                                        <a href="javascript:void(0)" onclick="uploadFile()">上传新图片</a><br />
                                        <a href="javascript:void(0)" onclick="removeImage()">删除图片</a>
                                    </td>
                                </tr>
                            </table>
                        </div>
                    </div>
                </td>
            </tr>
            @*<tr>
                    <td height="36">&nbsp;</td>
                    <td><input id="txtImageUrl" name="txtImageUrl" type="text" class="input_16" style="width:96%; " keyenter /></td>
                </tr>*@
           
            <tr>
                <td height="36">无限库存：</td>
                <td>
                    <select id="selectInfiniteStock" name="selectInfiniteStock" class="input_16" style="width:100px;" keyenter>
                        <option value="true">是</option>
                        <option value="false" selected>否</option>
                    </select>
                </td>
            </tr>
            <tr id="trStock" style="display:none">
                <td height="36">库存：</td>
                <td>
                    <input id="txtStock" name="txtStock" type="text" class="input_16" style="width:100px; " keyenter />
                    <input name="btnIncrement" type="button" class="btn_orange_small" id="btnIncrement" value="增加" onclick="showIncrement()" style="display:none" />
                    <input name="btnDecrement" type="button" class="btn_orange_small" id="btnDecrement" value="消减" onclick="showDecrement()" style="display:none" />
                </td>
            </tr>
            <tr>
                <td width="110" height="36">使用条件：</td>
                <td>
                    <textarea id='txtCondition' rows="3" style='width:96%; ' class="input_16" maxlength="150"></textarea>
                </td>
            </tr>
            <tr>
                <td width="110" height="36" valign="top">
                    <div style="margin-top:10px;">
                        详细说明：
                    </div>
                </td>
                <td>
                    <div style="width:96%; margin-top:10px;">
                        <div id="divDescriptionEditor" style='height:400px; '></div>
                    </div>
                </td>
            </tr>
            <tr>
                <td width="110">&nbsp;</td>
                <td>
                    <div style="width:96%;">
                        <div style="float:right;">
                            <input name="btnUpload" type="button" class="btn_white" id="btnUpload" value="上传图片" onclick="uploadDescriptionFile()" />
                        </div>
                        <div style="clear:both"></div>
                    </div>
                </td>
            </tr>
        </table>
    </form>

</div>

<div style=" background-color:#ccc; position:absolute; bottom:55px; left:20px;right:20px; height:1px;">

</div>

<div style="position:absolute; bottom:15px; left:20px;right:20px;">
    <div style="float:left;">
        <input name="btnRemove" type="button" class="btn_red" id="btnRemove" value="删 除" style="display:none" onclick="removeData()" />
    </div>

    <div style="float:right">
        <input name="btnSave" type="button" class="btn_blue" id="btnSave" value="保 存" onclick="save()" />
        <input name="btnCancel" type="button" class="btn_blue" id="btnCancel" value="取 消" onclick="cancel()" />
    </div>
    <div style="clear:both">
    </div>
</div>
@Helpers.FileUpload()
